package cn.tedu.ivos.audit.service.impl;

import cn.tedu.ivos.application.mapper.ApplicationMapper;
import cn.tedu.ivos.application.pojo.entity.Application;
import cn.tedu.ivos.audit.mapper.AuditMapper;
import cn.tedu.ivos.audit.pojo.dto.AuditQuery;
import cn.tedu.ivos.audit.pojo.dto.AuditSaveParam;
import cn.tedu.ivos.audit.pojo.entity.Audit;
import cn.tedu.ivos.audit.pojo.vo.AuditVO;
import cn.tedu.ivos.audit.service.AuditService;
import cn.tedu.ivos.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos.base.enums.AuditStatusEnum;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

@Service
@Slf4j
@Transactional
public class AuditServiceImpl implements AuditService {
    @Autowired
    AuditMapper auditMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ApplicationMapper applicationMapper;

    @Override
    public void insertAudit(Application application) {
        log.debug("为申请单生成对应审批单业务：{}",application);
        //1.获取此申请单中的审批人id集合[]
        List<Long> userIdList = application.getAuditUserIdList();
        //2.遍历审批人集合，有几个id，就生成几个审批单
        for (int i = 0; i < userIdList.size(); i++) {
            Audit audit = new Audit();
            //3.设置审批单批哪个申请单
            audit.setApplicationId(application.getId());
            //4.设置审批人id 谁来批
            audit.setAuditUserId(userIdList.get(i));
            //5.设置审批次序
            audit.setAuditSort(i);
            //6.设置审批单的初始状态
            if(i==0){
                audit.setAuditStatus(AuditStatusEnum.MY_PENGDING.getCode());
            }else {
                audit.setAuditStatus(AuditStatusEnum.PENGDING.getCode());
            }
            //7.设置创建时间
            audit.setCreateTime(new Date());
            //8.新增审批数据入库
            auditMapper.insert(audit);
        }
    }

    @Override
    public List<AuditVO> selectAuditByApplicationId(Long id) {
        return auditMapper.selectAuditByApplicationId(id);
    }

    @Override
    public List<AuditVO> selectAudit(AuditQuery auditQuery) {
        log.debug("查询审批单业务：{}",auditQuery);
       List<AuditVO> list= auditMapper.select(auditQuery);
       //依次遍历得到每个审批VO，补全它的审批人数据
        for (int i = 0; i < list.size(); i++) {
            AuditVO  auditVO = list.get(i);
            assignAuditUserList(auditVO);
        }
       return list;
    }

    @Override
    public void updateAudit(AuditSaveParam auditSaveParam) {
        log.debug("更新审批业务：{}",auditSaveParam);
        Audit audit = new Audit();
        BeanUtils.copyProperties(auditSaveParam,audit);
        audit.setUpdateTime(new Date());
        auditMapper.update(audit);
        //更新当前审批单后，准备更新当前审批单对应的申请单
        Application application = new Application();
        application.setId(audit.getApplicationId());
        application.setUpdateTime(new Date());
        //判断前端传过来的是"通过"操作还是驳回操作，分别做不同的后续处理
        if(audit.getAuditStatus().equals(ApplicationStatusEnum.AUDITED.getCode())){  //通过
            //继续查其他审批单：其他审批单与当前审批单 批同一个审批单
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            //根据申请单id查询当前申请单对应的所有未审批单总数(注意：单签审批单已通过了！)
            Integer count = auditMapper.selectRestAuditCount(auditQuery);
            if(count>0){  //还有未审批的审批单
                auditQuery.setAuditSort(audit.getAuditSort()+1);
                List<AuditVO> auditVOList = auditMapper.select(auditQuery);
                if(auditVOList != null && auditVOList.size()>0){
                    AuditVO auditVO = auditVOList.get(0);
                    //创建第2个审批单对象用于数据库更新
                    Audit audit2 = new Audit();
                    audit2.setId(auditVO.getId());
                    audit2.setAuditStatus(AuditStatusEnum.MY_PENGDING.getCode());
                    auditMapper.update(audit2);
                }
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.update(application);
            }else {//没有未审批的审批单，我是最后一个
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.update(application);
            }
        }else {  //驳回
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            List<AuditVO> auditVOList = auditMapper.select(auditQuery);
            //先判断数据是否为空
            if(auditVOList != null && auditVOList.size()>0){
                for (int i = 0; i < auditVOList.size(); i++) {
                    AuditVO auditVO = auditVOList.get(i);
                    if(auditVO.getAuditStatus().equals(AuditStatusEnum.PENGDING.getCode())){
                        auditMapper.deleteById(auditVO.getId());
                    }
                }
            }
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(auditSaveParam.getRejectReason());
            applicationMapper.update(application);
        }
    }

    private void assignAuditUserList(AuditVO auditVO) {
        List<Long> auditUserIdList = new ArrayList<>();
        List<String> auditUsernameList = new ArrayList<>();
        //根据审批单VO中的申请单id，得到审批此申请单的所有审批单
        List<AuditVO> auditVOList = auditMapper.selectAuditByApplicationId(auditVO.getApplicationId());
        //遍历每个审批单，获取每个审批人的id与姓名
        for (int i = 0; i < auditVOList.size(); i++) {
            Long userId = auditVOList.get(i).getAuditUserId();
            auditUserIdList.add(userId);
            UserVO user = userMapper.selectById(userId);
            auditUsernameList.add(user.getUsername());
        }
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String username : auditUsernameList){
            stringJoiner.add(username);
        }
        auditVO.setAuditUserIdList(auditUserIdList);
        auditVO.setAuditUsernameList(stringJoiner.toString());
    }
}
